<?php
// +----------------------------------------------------------------------
// | 分类Category模型
// +----------------------------------------------------------------------
// | Author: Eric <ieyangxiaoguo@126.com>
// +----------------------------------------------------------------------
// | Copyright ©2017 http://www.zzuyxg.top All rights reserved.
// +----------------------------------------------------------------------
// | 2017年10月10日
// +----------------------------------------------------------------------
namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;

class CategoryModel extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';//警告！delete_time，一定要默认为NULL！想知道原因，自己可以试试看。

    public function articles(){
        return $this->hasMany('ArticleModel','category_id');
    }

    /**
     * 分类添加
     * @param array $data
     * @return bool|mixed
     * @throws \think\exception\PDOException
     */
    public function addCategory($data = [])
    {
        self::startTrans();
        try{
            $this->allowField(true)->save($data);
            $id = $this->id;
            if (empty($data['parent_id'])){
                $this->where('id',$id)->update(['path'=>'0-'.$id]);
            }else{
                $parentPath = $this->where('id',intval($data['parent_id']))->value('path');
                $this->where('id',$id)->update(['path'=>$parentPath.'-'.$id]);
            }
            self::commit();
            return $id;
        }catch (\Exception $exception){
            self::rollback();
            return false;
        }
    }

    /**
     * 编辑文章分类
     * @param $data
     * @return bool
     * @throws \think\exception\DbException
     */
    public function editCategory($data)
    {
        $id = intval($data['id']);
        $parentId = intval($data['parent_id']);
        $oldCategory = $this->get($id);

        if (empty($oldCategory)) {
            return false;
        }

        if (empty($parentId)) {
            $newPath = '0-' . $id;
        } else {
            $parentPath = $this->where('id', intval($data['parent_id']))->value('path');
            if ($parentPath === false)
                return false;

            $newPath = "$parentPath-$id";
        }

        $data['path'] = $newPath;
        $this->isUpdate(true)->allowField(true)->save($data, ['id' => $id]);

        $children = $this->field('id,path')->where('path', 'like', "%-$id-%")->all();

        if (!empty($children)) {
            foreach ($children as $child) {
                $childPath = str_replace($oldCategory['path'] . '-', $newPath . '-', $child['path']);
                $this->isUpdate(true)->save(['path' => $childPath], ['id' => $child['id']]);
            }
        }

        return true;
    }

}
